package com.chenyue.cm.api.sms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenyue.cm.api.sms.service.JdSmsRecordService;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.ConstantValues;
import com.chenyue.cm.common.constant.RedisPrefix;
import com.chenyue.cm.common.utils.RequestUtil;
import com.chenyue.cm.sms.ApiRegisterModel;
import com.chenyue.cm.sms.SmsClient;
import com.chenyue.cm.sms.domain.JdSmsRecord;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.user.service.JdAppUserService;
import com.chenyue.cm.utils.MD5Util;
import com.chenyue.cm.utils.RedisUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

/**
 * @author libingxing
 * @date 2021-07-08
 */
@Api(value = "短信模块", tags = "验证码")
@ApiSort(10)
@RestController
@RequestMapping("/api/sms")
public class JdSmsRecordController {

    private final JdSmsRecordService jdSmsRecordService;

    private final JdAppUserService jdAppUserService;

    private final RedisUtils redisUtils;

    public JdSmsRecordController(JdSmsRecordService jdSmsRecordService, JdAppUserService jdAppUserService, RedisUtils redisUtils) {
        this.jdSmsRecordService = jdSmsRecordService;
        this.jdAppUserService = jdAppUserService;
        this.redisUtils = redisUtils;
    }

    /**
     * 获取验证码
     *
     * @param mobile 手机号
     * @return Success
     */
    @GetMapping("/getVerifyCode")
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "手机号", name = "mobile", dataType = "string", required = true),
            @ApiImplicitParam(value = "1注册", name = "type", dataType = "string", required = true),
            @ApiImplicitParam(value = "权限校验", name = "sign", dataType = "string", required = true)
    })
    public Success<Object> getVerifyCode(
            String mobile,
            @RequestParam(defaultValue = "2") Integer type,
            String sign, HttpServletRequest request
    ) {
        String salt = "ZHE_GE_JIE_KOU_YI_JIN_JIA_MI_LE";
        final String md5 = MD5Util.getMD5(mobile + salt, false, 32);
        if (!md5.equalsIgnoreCase(sign)) {
            return Success.error("权限不足");
        }
        final String ipAddr = RequestUtil.getIpAddr(request);
        System.err.println(ipAddr);
        QueryWrapper<JdSmsRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile).last(" limit 1");
        JdSmsRecord smsRecord = jdSmsRecordService.getOne(wrapper);
        if (smsRecord != null) {
//            当前时间 - 发送时间 = 间隔时间
            long left = System.currentTimeMillis() - smsRecord.getCt().getTime();
//            1分钟
            if (left < ConstantValues.ONE_MINUTE_MIL) {
                return Success.error("发送请求过于频繁");
            }
        }

        if (type == 1) {
            final JdAppUser one = jdAppUserService.lambdaQuery().eq(JdAppUser::getMobile, mobile).one();
            if (one != null) {
                return Success.error("该手机号已注册");
            }
        }

        String verifyCode = RandomStringUtils.randomNumeric(6);
//        发送短信
        String errorMsg = SmsClient.sendMsg(mobile, verifyCode);
        if (StringUtils.isEmpty(errorMsg)) {
//            成功记录入库
            JdSmsRecord record = new JdSmsRecord();
            record.setMobile(mobile);
            record.setCode(verifyCode);
            record.setCt(Calendar.getInstance().getTime());
            record.setUseFor(1);
            record.setIpSource(ipAddr);
            jdSmsRecordService.save(record);
//            缓存用于核对
            ApiRegisterModel model = new ApiRegisterModel();
            model.setVerifyCode(verifyCode);
            long expireTime = System.currentTimeMillis() + ConstantValues.VERIFY_CODE_EXPIRE;
            String md5Code = MD5Util.getMD5(RedisPrefix.LOGIN_USER + mobile + expireTime + verifyCode, false, 32);
            model.setExpireTime(expireTime + "");
            model.setMd5Code(md5Code);
            redisUtils.set(RedisPrefix.VERIFY_CODE + mobile, model, ConstantValues.VERIFY_CODE_EXPIRE);
            return Success.success();
        } else {
            return Success.error(errorMsg);
        }
    }

    public static void main(String[] args) {
        System.err.println(RandomStringUtils.randomNumeric(6));
    }

}
